//
//  OAuthViewController.swift
//  新浪微播
//
//  Created by lxw on 15/12/16.
//  Copyright © 2015年 lxw. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

class OAuthViewController: UIViewController {
    let webView = UIWebView()
    
    @objc private func close(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    @objc private func defaultAccount(){
        let jsString="document.getElementById('userId').value='18515803697',document.getElementById('passwd').value ='lenovo12' "
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    override func loadView(){
        view = webView
        webView.delegate = self
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        loadOAuthPage()
        setNavBar()
        // Do any additional setup after loading the view.
    }
         //  MARK:  加载授权页面
    private  func  loadOAuthPage(){
      //  print("----+++")
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        let url = NSURL(string: urlString)
        webView.loadRequest(NSURLRequest(URL: url!))
        
    }
    
       //  MARK: 设置导航条
    private func setNavBar(){
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动添存", style: .Plain, target: self, action: "defaultAccount")
    }
}

    extension OAuthViewController:UIWebViewDelegate{
        func webViewDidStartLoad(webView:UIWebView){
            SVProgressHUD.show()
        }
        func webViewDidFinishLoad(webView:UIWebView){
            SVProgressHUD.dismiss()
        }
        
        func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool{
            guard let urlString = request.URL?.absoluteString else{
                return false
            }
            if urlString.hasPrefix("https://api.weibo.com/"){
                //希望加载的页面
                return true
            }
            if !urlString.hasPrefix("http://www.baidu.com"){
                //一定不是请求成功后的回调 同样也不会是 我们希望加载的页面
                return false
            }
            //程序走到这里一定是请求成功后的回调
            print(urlString)
           //解析字符串获取code 码
            //query 获取到url 中参数部分键值
            let query = request.URL?.query
            if let q = query {
                //字符串截取操作
                let codeStr = "code="
                let code = q.substringFromIndex(codeStr.endIndex)
                //加载用户token
                loadAccessToken(code)
            }
            return true
        }
    private  func loadAccessToken(code:String){
        
      UserAccountViewModel().loadAccessToken(code) { (isSuccess) -> () in
        if isSuccess{
            print("登陆成功")
            self.dismissViewControllerAnimated(false, completion: { () -> Void in
                //等待 被modal出来的页面 彻底被回收是 再发出页面切换的通知
                NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchRootVCNotification, object: "Welcome")
                
                print("come here")
        })
          //  self.close()
        }else{
            print("登陆失败")
        }
        
        }
        }
    
}













